package com.retail.common.exception;

import com.retail.common.result.Result;
import com.retail.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author retail
 * @since 2024-01-01
 */
@Slf4j
@RestControllerAdvice
@Order(1) // 设置最高优先级
public class GlobalExceptionHandler {

  /**
   * 处理业务异常
   */
  @ExceptionHandler(BusinessException.class)
  @ResponseStatus(HttpStatus.OK)
  public Result<Void> handleBusinessException(BusinessException e) {
    log.error("业务异常: {}", e.getMessage(), e);
    return Result.error(e.getCode(), e.getMessage());
  }

  /**
   * 处理参数校验异常
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    log.error("参数校验异常: {}", e.getMessage(), e);
    FieldError fieldError = e.getBindingResult().getFieldError();
    String message = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
    return Result.error(ResultCode.PARAM_ERROR.getCode(), message);
  }

  /**
   * 处理参数绑定异常
   */
  @ExceptionHandler(BindException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public Result<Void> handleBindException(BindException e) {
    log.error("参数绑定异常: {}", e.getMessage(), e);
    FieldError fieldError = e.getBindingResult().getFieldError();
    String message = fieldError != null ? fieldError.getDefaultMessage() : "参数绑定失败";
    return Result.error(ResultCode.PARAM_ERROR.getCode(), message);
  }

  /**
   * 处理约束违反异常
   */
  @ExceptionHandler(ConstraintViolationException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
    log.error("约束违反异常: {}", e.getMessage(), e);
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    String message = violations.iterator().next().getMessage();
    return Result.error(ResultCode.PARAM_ERROR.getCode(), message);
  }

  /**
   * 处理HTTP消息不可读异常（JSON解析异常）
   */
  @ExceptionHandler(HttpMessageNotReadableException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public Result<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
    log.error("HTTP消息不可读异常: {}", e.getMessage(), e);
    return Result.error(ResultCode.PARAM_ERROR.getCode(), "请求参数格式错误");
  }

  /**
   * 处理非法参数异常
   */
  @ExceptionHandler(IllegalArgumentException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public Result<Void> handleIllegalArgumentException(IllegalArgumentException e) {
    log.error("非法参数异常: {}", e.getMessage(), e);
    return Result.error(ResultCode.PARAM_ERROR.getCode(), e.getMessage());
  }

  /**
   * 处理运行时异常（放在最后，避免捕获更具体的异常）
   * 注意：HttpMessageNotReadableException继承自RuntimeException，所以这个处理器必须在HttpMessageNotReadableException之后
   * 暂时注释掉，避免与HttpMessageNotReadableException冲突
   */
  // @ExceptionHandler(RuntimeException.class)
  // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  // public Result<Void> handleRuntimeException(RuntimeException e) {
  // log.error("运行时异常: {}", e.getMessage(), e);
  // return Result.error(ResultCode.ERROR.getCode(), "系统异常，请联系管理员");
  // }

  /**
   * 处理其他异常
   */
  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public Result<Void> handleException(Exception e) {
    log.error("系统异常: {}", e.getMessage(), e);
    return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "系统异常，请联系管理员");
  }
}
